import 'package:eplorex/dao/user_contact_dao.dart';
import 'package:eplorex/models/contact/contact_model.dart';
import 'package:eplorex/pages/message/contact/IndexBarWidget.dart';
import 'package:eplorex/pages/message/contact/search_widget.dart';
import 'package:eplorex/pages/message/group/contact_group.dart';
import 'package:eplorex/pages/my/follow_page.dart';
import 'package:eplorex/pages/my/user_profile_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'ItemCell.dart';
import 'contact_define.dart';

class ContactPage extends StatefulWidget {
  const ContactPage({super.key,required this.onMessage});

  final ValueChanged onMessage;

  @override
  State<ContactPage> createState() => _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {

  late ScrollController _scrollController;
  Future<List<ContactModel>?>? _contacts;
  List<ContactModel> _contactDynamicsData=[];
  List<ContactModel> _contactsData=[];
//字典 里面放item和高度对应的数据
  final Map<String, double> _groupOffsetMap = {
    INDEX_WORDS[0]: 0.0, //放大镜
    INDEX_WORDS[1]: 0.0, //⭐️
  };

  String searchStr = '';
  bool _load=false;

  @override
  void initState() {
    _scrollController=ScrollController();
    _contacts=UserContactDao.queryUserContactFriends();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            SearchWidget(
              onSearchChange: (str) {
                _contactDynamicsData.clear();
                if(str.isNotEmpty){
                  for(ContactModel item in _contactsData){
                    if(item.name!.contains(str)){
                      _contactDynamicsData.add(item);
                    }
                  }
                }else{
                  _contactDynamicsData.addAll(_contactsData);
                }
                setState(() {});

              },
            ),
            ItemCell(name:'新增朋友',isIcon: true,imageUrl: "assets/group_member.png",onAvatarTap: (){
              Navigator.of(context).push(MaterialPageRoute(builder: (_)=>FollowPage()));
            },),
            ItemCell(name:'群聊',isIcon: true,imageUrl: "assets/group_member.png",onAvatarTap: (){
              Navigator.of(context).push(MaterialPageRoute(builder: (_)=>ContactGroupPage()));
            },),
            FutureBuilder(future: _contacts, builder: (BuildContext context, AsyncSnapshot snapshot){
              if(snapshot.connectionState==ConnectionState.waiting || !snapshot.hasData){
                return const Expanded(child: CircularProgressIndicator());
              }
              _contactsData=  snapshot.data;
              _sortData(_contactsData!);

              if(!_load){
                _load=true;
                _contactDynamicsData.addAll(_contactsData);
              }

              return ListView.builder(
                  shrinkWrap: true,
                  controller: _scrollController ,
                  itemBuilder: (BuildContext context, int index)=>
                      itemBuilder(_contactDynamicsData,context,index),itemCount:_contactDynamicsData?.length);
            }),
          ],
        ),
        // Positioned(
        //     right: 0, top: screenHeight(context) / 8, child: IndexBarWidget(indexBarCallBack: (String str) {
        //       if(_groupOffsetMap[str]!=null){
        //         // _scrollController.animateTo(_groupOffsetMap[str]!, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
        //       }
        // },)),
      ],
    );
  }

  void _sortData( List<ContactModel> contactModels){
    contactModels.sort((o1,o2)=>o1.letter!.compareTo(o2.letter!));
    var groupOffset = 0.0;
    for (int i = 0; i < contactModels.length; i++) {
      if (i < 1) {
        //第一个cell一定有头
        _groupOffsetMap.addAll({contactModels[i].letter!: groupOffset});
        groupOffset += cellHeight + cellHeaderHeight;
      } else if (contactModels[i].letter == contactModels[i - 1].letter) {
        // 相同的时候只需要加cell的高度
        groupOffset += cellHeight;
      } else {
        //第一个cell一定有头
        _groupOffsetMap.addAll({contactModels[i].letter!: groupOffset});
        groupOffset += cellHeight + cellHeaderHeight;
      }
    }
    print('dc------$_groupOffsetMap');
    // setState(() {});
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Widget? itemBuilder(List<ContactModel>? contactModels,BuildContext context, int index) {
    ContactModel contactModel= contactModels![index];
    return ItemCell(name:contactModel.name ?? '未知',imageUrl: contactModel.avatar,onAvatarTap: (){
      {
       Navigator.of(context).push(MaterialPageRoute(builder: (_)=>UserProfilePage(userId: contactModel.userId!,)));
      }
    },);
  }
}
